package loginuser

import (
	"encoding/json"
	"os"
	"path/filepath"
	"sync"

	"gitee.com/tomatomeatman/golang-repository/bricks3/utils/app/moduleutil"
	Log "github.com/cihub/seelog"
)

var (
	loginUserBusinessInfo     *LoginUserBusinessInfo
	loginUserBusinessInfoOnce sync.Once
)

type LoginUserBusinessInfo struct {
	DbName       string `json:"dbName"`        //所用库
	TableName    string `json:"tableName"`     //所用表名",
	Id           string `json:"sId"`           //记录编号字段名",
	Name         string `json:"sName"`         //用户名字段名",
	No           string `json:"sNo"`           //用户唯一标识字段名",
	Pass         string `json:"sPass"`         //用户密码字段名",
	Type         string `json:"sType"`         //类型",
	State        string `json:"iState"`        //账户状态字段名",
	StateValue   string `json:"iStateValue"`   //有效状态值",
	Memo         string `json:"sMemo"`         //备注
	Creator      string `json:"sCreator"`      //创建人员
	CreateDate   string `json:"dCreateDate"`   //创建时间
	ModifiedDate string `json:"dModifiedDate"` //修改人员
	Modifieder   string `json:"sModifieder"`   //修改时间
	Index        string `json:"iIndex"`        //序号
	Version      string `json:"iVersion"`      //版本号
	DelSign      string `json:"iDelSign"`      //删除标志
}

func GetLoginUserBusinessInfo() *LoginUserBusinessInfo {
	loginUserBusinessInfoOnce.Do(func() {
		root := ""
		exePath, err := os.Executable()
		if err != nil {
			root = "."
		}

		root, _ = filepath.EvalSymlinks(filepath.Dir(exePath))

		business := filepath.Join(root, "config/LoginBusiness.json")

		if _, err := os.Stat(business); os.IsNotExist(err) {
			Log.Error("业务配置文件不存在:", "config/LoginBusiness.json")
			return
		}

		data, err := os.ReadFile(business)
		if err != nil {
			Log.Error("读取配置文件发生异常:", err)
			return
		}

		temp := LoginUserBusinessInfo{}
		err = json.Unmarshal(data, &temp)
		if err != nil {
			Log.Error("配置信息转实体发生异常:", err)
			return
		}

		loginUserBusinessInfo = &temp
	})

	if loginUserBusinessInfo == nil {
		loginUserBusinessInfo = &LoginUserBusinessInfo{
			DbName:     moduleutil.GetMainDb(),
			TableName:  "LoginUser",
			Id:         "sId",
			Name:       "sName",
			No:         "sNo",
			Pass:       "sPass",
			State:      "iState",
			Type:       "sType",
			StateValue: "1",
		}
	}

	return loginUserBusinessInfo
}
